package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.Address;
import cn.edu.tju.core.model.Cart;
import cn.edu.tju.core.model.Merchant;
import cn.edu.tju.core.model.Order;
import cn.edu.tju.core.model.Product;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.utils.HttpResult;
import cn.edu.tju.elm.service.AddressService;
import cn.edu.tju.elm.service.CartService;
import cn.edu.tju.elm.service.MerchantService;
import cn.edu.tju.elm.service.OrderService;
import cn.edu.tju.elm.service.ProductService;
import cn.edu.tju.elm.service.UserService;
import cn.edu.tju.elm.vo.AdminAuthRequest;
import cn.edu.tju.elm.vo.BusinessRequest;
import cn.edu.tju.elm.vo.FoodRequest;
import cn.edu.tju.elm.vo.MerchantOwnerRequest;
import cn.edu.tju.elm.controller.AddressRequest;
import cn.edu.tju.elm.controller.CartRequest;
import cn.edu.tju.elm.controller.OrderRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: myapp-1.0 - ApiController
 * <p>Powered 龙少 作者名 On 2025-09-25 10:16:03
 * author: 龙少
 * version: 版本
 * since: 1.8以后的版本都能用
 */
@RestController
@RequestMapping("/api")
public class ApiController {

  @Autowired
  private UserService userService;

  @Autowired
  private MerchantService merchantService;

  @Autowired
  private ProductService productService;

  @Autowired
  private CartService cartService;

  @Autowired
  private AddressService addressService;

  @Autowired
  private OrderService orderService;

  private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

  @PostMapping("/auth")
  public HttpResult adminLogin(@RequestBody AdminAuthRequest req) {
    if (req == null || req.getUsername() == null || req.getPassword() == null) {
      return HttpResult.fail("用户名或密码不能为空");
    }

    // 验证管理员账号密码
    if ("admin".equals(req.getUsername()) && "admin".equals(req.getPassword())) {
      // 创建管理员用户对象返回
      User adminUser = new User();
      adminUser.setId(0); // 管理员ID设为0
      adminUser.setUsername("admin");
      adminUser.setRole(1); // 假设1为管理员角色
      return HttpResult.ok(adminUser);
    } else {
      // 查询数据库中role=1或role=2的用户（管理员或店主）
      QueryWrapper<User> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("username", req.getUsername())
                  .and(wrapper -> wrapper.eq("role", 1).or().eq("role", 2));

      User user = userService.getOne(queryWrapper);

      if (user != null && passwordEncoder.matches(req.getPassword(), user.getPassword())) {
        // 密码验证成功，返回用户信息
        return HttpResult.ok(user);
      } else {
        return HttpResult.fail("身份认证失败");
      }
    }
  }

  @PostMapping("/persons")
  public HttpResult createMerchantOwner(@RequestBody MerchantOwnerRequest req) {
    if (req == null) {
      return HttpResult.fail("请求参数不能为空");
    }

    // 验证必填字段
    if (req.getUsername() == null || req.getUsername().trim().isEmpty()) {
      return HttpResult.fail("用户名不能为空");
    }




    try {
      // 检查用户名是否已存在
      User existingUser = userService.getOne(new QueryWrapper<User>().eq("username", req.getUsername()));
      if (existingUser != null) {
        return HttpResult.fail("用户名已存在");
      }



      // 创建用户账号
      User user = new User();
      user.setUsername(req.getUsername());
      user.setFirstName(req.getFirstName());
      user.setLastName(req.getLastName());
      user.setRole(2);

      boolean userSaved = userService.save(user);
      if (!userSaved) {
        return HttpResult.fail("创建用户账号失败");
      }





      // 返回成功结果，包含用户和商家信息
      java.util.Map<String, Object> result = new java.util.HashMap<>();
      result.put("user", user);

      return HttpResult.ok(result);

    } catch (Exception e) {
      return HttpResult.fail("创建店主失败：" + e.getMessage());
    }
  }

  @PostMapping("/businesses")
  public HttpResult createBusiness(@RequestBody BusinessRequest req) {
    if (req == null) {
      return HttpResult.fail("请求参数不能为空");
    }

    // 验证必填字段
    if (req.getBusinessName() == null || req.getBusinessName().trim().isEmpty()) {
      return HttpResult.fail("商家名称不能为空");
    }

    if (req.getBusinessOwner() == null || req.getBusinessOwner().getId() == null) {
      return HttpResult.fail("商家所有者ID不能为空");
    }

    try {
      // 验证用户是否存在
      User owner = userService.getById(req.getBusinessOwner().getId());
      if (owner == null) {
        return HttpResult.fail("指定的用户不存在");
      }

      // 创建商家信息
      Merchant merchant = new Merchant();
      merchant.setBusinessName(req.getBusinessName());
      // 可以设置一些默认值
      merchant.setRating(new java.math.BigDecimal("0.0"));
      merchant.setMonthlySales(0);
      merchant.setStartingPrice(new java.math.BigDecimal("0.00"));
      merchant.setDeliveryFee(new java.math.BigDecimal("0.00"));
      merchant.setBusinessOwner(req.getBusinessOwner().getId());
      boolean merchantSaved = merchantService.save(merchant);
      if (!merchantSaved) {
        return HttpResult.fail("创建商家失败");
      }

      // 返回成功结果
      java.util.Map<String, Object> result = new java.util.HashMap<>();
      result.put("merchant", merchant);
      result.put("owner", owner);

      return HttpResult.ok(result);

    } catch (Exception e) {
      return HttpResult.fail("创建商家失败：" + e.getMessage());
    }
  }

  @PostMapping("/foods")
  public HttpResult createFood(@RequestBody FoodRequest req) {
    if (req == null) {
      return HttpResult.fail("请求参数不能为空");
    }

    // 验证必填字段
    if (req.getFoodName() == null || req.getFoodName().trim().isEmpty()) {
      return HttpResult.fail("商品名称不能为空");
    }

    if (req.getFoodPrice() == null) {
      return HttpResult.fail("商品价格不能为空");
    }

    if (req.getBusiness() == null || req.getBusiness().getId() == null) {
      return HttpResult.fail("商家ID不能为空");
    }

    try {
      // 验证商家是否存在
      Merchant merchant = merchantService.getById(req.getBusiness().getId());
      if (merchant == null) {
        return HttpResult.fail("指定的商家不存在");
      }

      // 创建商品信息
      Product product = new Product();
      product.setName(req.getFoodName());
      product.setPrice(req.getFoodPrice());
      product.setMerchantId(req.getBusiness().getId());
      // 可以设置一些默认值
      product.setDescription("美味商品");

      boolean productSaved = productService.save(product);
      if (!productSaved) {
        return HttpResult.fail("创建商品失败");
      }

      // 返回成功结果
      java.util.Map<String, Object> result = new java.util.HashMap<>();
      result.put("product", product);
      result.put("merchant", merchant);

      return HttpResult.ok(result);

    } catch (Exception e) {
      return HttpResult.fail("创建商品失败：" + e.getMessage());
    }
  }

  @PostMapping("/carts")
  public HttpResult createCart(@RequestBody CartRequest req) {
    try {
      // 验证请求参数
      if (req.getFood() == null || req.getFood().getId() == null) {
        return HttpResult.fail("food.id 不能为空");
      }

      if (req.getQuantity() == null || req.getQuantity() < 1 || req.getQuantity() > 10) {
        return HttpResult.fail("quantity 必须在1-10之间");
      }

      // 检查商品是否存在
      Product product = productService.getById(req.getFood().getId());
      if (product == null) {
        return HttpResult.fail("商品不存在");
      }

      // 创建购物车对象
      Cart cart = new Cart();
      cart.setUserId(1); // 临时设置为1，实际应用中需要从登录用户获取
      cart.setProductId(req.getFood().getId());
      cart.setQuantity(req.getQuantity());
      cart.setPrice(product.getPrice());
      cart.setProductName(product.getName());
      cart.setStatus(0); // 0-未下单

      // 保存购物车
      boolean saved = cartService.save(cart);
      if (!saved) {
        return HttpResult.fail("保存购物车失败");
      }

      // 返回结果
      Map<String, Object> result = new HashMap<>();
      result.put("cart", cart);
      result.put("product", product);

      return HttpResult.ok(result);

    } catch (Exception e) {
      return HttpResult.fail("创建购物车失败：" + e.getMessage());
    }
  }

  @PostMapping("/addresses")
  public HttpResult createAddress(@RequestBody AddressRequest req) {
    try {
      // 验证必填字段
      if (req.getContactName() == null || req.getContactName().trim().isEmpty()) {
        return HttpResult.fail("联系人姓名不能为空");
      }
      if (req.getContactTel() == null || req.getContactTel().trim().isEmpty()) {
        return HttpResult.fail("联系电话不能为空");
      }
      if (req.getAddress() == null || req.getAddress().trim().isEmpty()) {
        return HttpResult.fail("地址不能为空");
      }

      // 创建地址对象
      Address address = new Address();
      address.setContactName(req.getContactName());
      address.setPhone(req.getContactTel());
      address.setDetail(req.getAddress());
      // 临时设置用户ID为1L，实际应用中应该从登录用户获取
      address.setUserId(1L);

      // 保存地址
      addressService.save(address);

      // 返回结果
      Map<String, Object> result = new HashMap<>();
      result.put("address", address);

      return HttpResult.ok(result);

    } catch (Exception e) {
      return HttpResult.fail("创建地址失败：" + e.getMessage());
    }
  }

  @PostMapping("/orders")
  public HttpResult createOrder(@RequestBody OrderRequest req) {
    try {
      // 验证必填字段
      if (req.getBusiness() == null || req.getBusiness().getId() == null) {
        return HttpResult.fail("商家信息不能为空");
      }
      if (req.getDeliveryAddress() == null || req.getDeliveryAddress().getId() == null) {
        return HttpResult.fail("配送地址不能为空");
      }

      // 验证商家是否存在
      Merchant merchant = merchantService.getById(req.getBusiness().getId());
      if (merchant == null) {
        return HttpResult.fail("指定的商家不存在");
      }

      // 验证地址是否存在
      Address address = addressService.getById(req.getDeliveryAddress().getId());
      if (address == null) {
        return HttpResult.fail("指定的配送地址不存在");
      }

      // 创建订单对象
      Order order = new Order();
      order.setName(merchant.getBusinessName() + "订单");
      order.setTotalPrice(new java.math.BigDecimal("0.00")); // 初始总价为0，实际应用中应计算购物车总价
      order.setUserId(1); // 临时设置用户ID为1，实际应用中应该从登录用户获取
      order.setStatus(0); // 0-未支付
      order.setQuantity(1); // 初始数量为1，实际应用中应计算购物车总数量

      // 保存订单
      orderService.save(order);

      // 返回结果
      Map<String, Object> result = new HashMap<>();
      result.put("order", order);
      result.put("merchant", merchant);
      result.put("deliveryAddress", address);

      return HttpResult.ok(result);

    } catch (Exception e) {
      return HttpResult.fail("创建订单失败：" + e.getMessage());
    }
  }
}
